package com.jxt.mina.server;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.jxt.mina.net.Connection;
import com.jxt.mina.session.SessionManager;



public class ServerHandler extends IoHandlerAdapter {
	Logger logger = Logger.getLogger(ServerHandler.class);
	private static final String CONNECTION = "CONNECTION";
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		 cause.printStackTrace();
		session.close(true);
		logger.info("服务器发送信息异常....");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		

		logger.info("ScoketSession Id==>：" + session.getId());
		logger.info("服务端接受到得数据为：" + message.toString());
		String str = message.toString().trim();
		
		if(str==null)
		return;
		//绑定id
		if(str.startsWith("bindUserId~>$&&")){	
			String uerId=str.substring(15, str.length());
			session.setAttribute("userId", uerId);
			SessionManager.getInstance().addAuthorizedIoSession(session);
		}
		try
		{
			JSONObject json = JSONObject.fromObject(message);
		}catch(Exception e){
			
			
			
		}
		
		
		Collection<IoSession> sess = session.getService()
		.getManagedSessions().values();
			logger.info(sess.size()+"=====>>>");
			for (IoSession ioSession : sess) {
				String sessionId = (String) ioSession
						.getAttribute("sessionId");
				//logger.info(sessionId+"=====>>>");
				
			}
		
		
//		SaveMessage smsg = new SaveMessage();
//		List list = new ArrayList();
//		String sendTime = "";
//		String msg = "";
//		String memberId = "";
//		
//
//	
//		if (str.length() == 32) { // 32位证明是刚登录~保存用户sessionId
//			String sessionId = (String) session.getAttribute("sessionId");
//			//System.out.println(sessionId);
//			if (sessionId == null) {
//				session.setAttribute("sessionId", str);
//				System.out.println("绑定userid="+session.getAttribute("sessionId"));
//			}
//			session.write(str);
//		}
//		
//		
//		Collection<IoSession> sess = session.getService()
//				.getManagedSessions().values();
//		logger.info(sess.size()+"=====>>>");
//		for (IoSession ioSession : sess) {
//			String sessionId = (String) ioSession
//					.getAttribute("sessionId");
//			logger.info(sessionId+"=====>>>");
//			
//		}
//		if (str.length() > 32) { // 大约32位认为是聊天信息
//			JSONObject json = JSONObject.fromObject(message);
//			Iterator iterator = json.keySet().iterator();
//			while (iterator.hasNext()) {
//				String key = iterator.next().toString();
//				System.out.println("key=" + key + ", val=" + json.get(key));
//				if (key.equals("listId")) {
//					JSONArray array = json.getJSONArray(key);
//					for (int i = 0; i < array.size(); i++) {
//						String listId = array.getString(i);
//						list.add(listId);
//					}
//				}
//				if (key.equals("sendTime")) {
//					sendTime = json.getString(key);
//				}
//				if (key.equals("message")) {
//					msg = json.getString(key);
//				}
//				if (key.equals("memberId")) {
//					memberId = json.getString(key);
////					session.setAttribute("sessionId", memberId);
//				}
//			}
//			// List sessionList = new ArrayList();
//
//			
//
//			for (int i = 0; i < list.size(); i++) {
//				String listId = (String) list.get(i);
//				boolean isOnline = false;
//				for (IoSession ioSession : sess) {
//					String sessionId = (String) ioSession
//							.getAttribute("sessionId");
//					//logger.info(sessionId+"=====>>>"+i);
//					if (listId.equals(sessionId)) {
//						//logger.info("=====>>>"+sessionId);
//						isOnline = true;
//						WriteFuture future=ioSession.write(message);
//						// Wait until the message is completely written out to the O/S buffer.
//						
//						future.addListener(new IoFutureListener() {  
//						    public void operationComplete(IoFuture future){  
//						        WriteFuture wfuture=(WriteFuture)future;  
//						        // 写入成功  
//						        if(wfuture.isWritten()){  
//						        	logger.info(" The message has been written successfully.");
//						            return;  
//						        }  
//						        logger.info("The messsage couldn't be written out completely for some reason.");
//						            // 写入失败，自行进行处理  
//						    }  
//						}); 
//						//future.join();
//						//if( future.isWritten() )  {
//						//	logger.info(" The message has been written successfully.");
//						//}  else  {
//						//	logger.info("The messsage couldn't be written out completely for some reason.");
//						  // The messsage couldn't be written out completely for some reason.
//						  // (e.g. Connection is closed)
//						//}
//
//					}
//				}
//				if(isOnline == false){
//					smsg.saveMsg(listId, memberId, sendTime, msg);
//				}			
//			}

	//	}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		// 发送消息成功之后，关闭session，即关闭与客户端的连接，短连接方式
		// session.close();
		// super.messageSent(session, message);
		logger.info("Sent " + message+"==and====IoSession"+session.getAttribute("sessionId"));  
		//logger.info("服务器发送信息成功....");
		//super.messageSent(session, message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		SessionManager.getInstance().removeAuthorizedIoSession(session);
		super.sessionClosed(session);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		// session.setAttribute("userId", UUID.randomUUID().toString());
		hackReadBufSize(session, 8* 1024);
		//管理session
		//Connection  connection=new Connection(session);
		//session.setAttribute(CONNECTION, connection);
		//SessionManager.getInstance().createClientSession(conn);
		
		logger.info("服务端与客户端创建连接...");
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		// logger.info("服务器进入空闲状态...");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.getConfig().setReadBufferSize(1024*2);
		logger.info("服务端与客户端连接打开.....");
	}
	
	
	/**
     * hack无权限类相关域
     */
    private void hackReadBufSize(IoSession session, int readBuf) {
        try {
            Method method = session.getClass().getDeclaredMethod("setReadBufferSize", int.class);

            method.setAccessible(true);

            method.invoke(session, readBuf);

        } catch (Exception e) {

        }
    }

}
